const util = require('../../utils/util');
const ClientService = require('../../service/admin/basic_client.service');
const excel = require('../../middleware/excel');
const fs = require('fs');

async function createClient(ctx) {
  const { userId } = util.decodeToken(ctx);
  const { cName, remark, state, orgName, taxNum, bankName, bankCard, billInfo, email, address, phone } = ctx.request.body;

  if (!cName) {
    return util.fail(ctx, '客户名不能为空');
  }

  try {
    const result = await ClientService.createClient({
      cName,
      remark,
      state,
      orgName,
      taxNum,
      bankName,
      bankCard,
      billInfo,
      email,
      address,
      phone,
      creater_id: userId,
      updata_id: userId
    });
    util.success(ctx, { id: result.id });
  } catch (error) {
    console.error('Create client error:', error.message);
    util.fail(ctx, error.message || '创建失败');
  }
}

async function deleteClients(ctx) {
  const { ids } = ctx.request.body;

  if (!Array.isArray(ids) || ids.length === 0) {
    return util.fail(ctx, '客户 ID 列表无效');
  }

  try {
    await ClientService.deleteClients(ids);
    util.success(ctx, '');
  } catch (error) {
    console.error('Delete clients error:', error.message);
    util.fail(ctx, error.message || '删除失败');
  }
}

async function updateClient(ctx) {
  const { userId } = util.decodeToken(ctx);
  const { id, cName, remark, state, orgName, taxNum, bankName, bankCard, billInfo, email, address, phone } = ctx.request.body;

  if (!id || !cName) {
    return util.fail(ctx, '客户 ID 或客户名不能为空');
  }

  try {
    await ClientService.updateClient({
      id,
      cName,
      remark,
      state,
      orgName,
      taxNum,
      bankName,
      bankCard,
      billInfo,
      email,
      address,
      phone,
      updata_id: userId
    });
    util.success(ctx, '');
  } catch (error) {
    console.error('Update client error:', error.message);
    util.fail(ctx, error.message || '更新失败');
  }
}

async function getClientList(ctx) {
  const { page = 1, limit = 10, cName, state, phone } = ctx.query;

  try {
    const result = await ClientService.getClientList({
      page: parseInt(page),
      limit: parseInt(limit),
      cName,
      state: state ? parseInt(state) : undefined,
      phone
    });
    util.success(ctx, result);
  } catch (error) {
    console.error('Get client list error:', error.message);
    util.fail(ctx, error.message || '查询失败');
  }
}

async function updateClientState(ctx) {
  const { userId } = util.decodeToken(ctx);
  const { id, state } = ctx.request.body;

  if (!id) {
    return util.fail(ctx, '客户 ID 列表无效');
  }
  const newState = state === 1017001 ? 1017002 : 1017001;
  try {
    await ClientService.updateClientState({ id, newState, updata_id: userId });
    util.success(ctx);
  } catch (error) {
    console.error('Update client state error:', error.message);
    util.fail(ctx, error.message || '状态更新失败');
  }
}

//导出客户数据
async function exportClient(ctx) {
  try {
    const { cName, state, phone } = ctx.request.body;
    await ClientService.exportClient(ctx, { cName, state, phone });
  } catch (error) {
    console.error('Export client error:', error.message);
    util.fail(ctx, error.message || '导出失败');
  }
}

async function importClient(ctx) {
  const file = ctx.request.files.file;
  const headerMap = {
    id: 'ID',
    cName: '客户名称',
    remark: '备注',
    state: '状态',
    orgName: '组织名称',
    taxNum: '税号',
    bankName: '开户银行',
    bankCard: '银行账号',
    billInfo: '发票信息',
    email: '邮箱',
    address: '地址',
    phone: '电话'
  };
  const data = await excel.readExcelStream(file, headerMap);
  util.success(ctx, data);
}

module.exports = {
  createClient,
  deleteClients,
  updateClient,
  getClientList,
  updateClientState,
  exportClient,
  importClient
};
